package com.duoduo.core.flyway;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DatabaseHelper {

	private String dbHost = "localhost";
	private int dbPort = 3306;
	private String dbName = "mysql";
	private String dbUsername = "root";
	private String dbPassword = "";
	private boolean useUnicode = true;
	private String characterEncoding = "utf-8";

	public void setDbHost(String dbHost) {
		this.dbHost = dbHost;
	}

	public void setDbPort(int dbPort) {
		this.dbPort = dbPort;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public void setDbUsername(String dbUsername) {
		this.dbUsername = dbUsername;
	}

	public void setDbPassword(String dbPassword) {
		this.dbPassword = dbPassword;
	}

	public void setUseUnicode(boolean useUnicode) {
		this.useUnicode = useUnicode;
	}

	public void setCharacterEncoding(String characterEncoding) {
		this.characterEncoding = characterEncoding;
	}

	private String getDbUrl(String name) {
		return String.format("jdbc:mysql://%s:%d/%s?useUnicode=%s&characterEncoding=%s", dbHost, dbPort, name,
				(useUnicode ? "true" : "false"), characterEncoding);
	}

	public boolean existsDb(String name) {
		boolean exists = true;
		try {
			Connection connection = DriverManager.getConnection(getDbUrl(name), dbUsername, dbPassword);
			connection.close();
		} catch (Exception e) {
			exists = false;
		}
		return exists;
	}

	/**
	 * 创建需要的数据库
	 */
	public void prepareDatabase() {
		try {
			Class.forName("com.mysql.jdbc.Driver");

			// 连接已经存在的数据库，如：mysql
			Connection connection = DriverManager.getConnection(getDbUrl("mysql"), dbUsername, dbPassword);
			Statement statement = connection.createStatement();

			// 创建数据库
			statement.executeUpdate("create database if not exists `" + dbName + "` default character set utf8");

			statement.close();
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
